package com.mobi.Survey;

import java.io.File;
import java.io.IOException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.appbucks.sdk.AppBucksBanner;
import com.mobi.Survey.controller.SurveyDetailPojo;
import com.mobi.Survey.uicomponents.ControlFactory;
import com.mobi.Survey.utils.Helper;
import com.mobi.Survey.video.VideoPlayer;
import com.mobi.Survey.video.YouTubeUtility;

public class SurveyDetailSingleControl extends AbstractDetailScreen
{

	// UI Vars

	private TextView txtPageNumber;
	private Button btnPrevious;
	private Button btnNext;
	private ProgressBar pbImageLoading;
	private int currentCompIndex = 0;
	private int lastComponent = 0;
	private Bitmap focusedImage;
	private String fontColor;
	private SparseArray<DownloadStatus> downloadTracker = new SparseArray<DownloadStatus>(
			10);;
	private SparseArray<ImageView> imageViews = new SparseArray<ImageView>();
	private SparseArray<String> videoUrls = new SparseArray<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		fontColor = survey.getFontColor();

	}

	@Override
	protected int getLayoutId()
	{

		return LayoutIds.DETAIL_SCREEN_SINGLE_CONTROL;
	}

	@Override
	protected void onStart()
	{

		super.onStart();
		if (null != fontColor && fontColor.length() > 0)
		{
			txtPageNumber.setTextColor(Color.parseColor("#" + fontColor));
		} else
		{
			txtPageNumber.setTextColor(Color.WHITE);
		}
	}

	DownloadImageFile imageDownloader;

	protected void createViews()
	{

		ViewGroup vg = (ViewGroup) findViewById(R.id.llSurveyDetailSingle);

		if (vg != null && sdps != null && sdps.size() > 0)
		{

			// boolean firstImage = true;
			for (SurveyDetailPojo sdp : sdps)
			{

				View v = ControlFactory.createControl(sdp, this, false);

				if (v == null)
				{
					printLogMessage("Invalid Control Found with Control No: "
							+ sdp.getControlType());
					continue;
				}

				v.setVisibility(View.GONE);

				// if control type is Video View perform necessary action on
				// video control
				if (sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
				{

					performActionOnVideoControl(sdp, v);

				}
				// if control type is Image View perform necessary action on
				// Image control

				if (sdp.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW)
				{

					performActionOnImageControl(sdp, v);

				}

				vg.addView(v);
				views.add(v);

			}

			// if first control is image or video let the progress bar visible
			// we will invisible it later after image load
			byte ctrlType = sdps.get(0).getControlType();
			if (ctrlType == ControlFactory.CONTROL_IMAGE_VIEW
					|| ctrlType == ControlFactory.CONTROL_VIDEO_VIEW)
			{
				pbImageLoading.setVisibility(View.VISIBLE);
			}
			imageDownloader = new DownloadImageFile();

			imageDownloader.execute();

			lastComponent = views.size() - 1;

			// because it is single component per screen we are making first
			// item visible
			views.get(0).setVisibility(View.VISIBLE);
			btnSubmit.setVisibility(View.GONE);
			refreshButtonsState();
			// setting current page number of total page
			StringBuilder sbTxtPageNumber = new StringBuilder();
			sbTxtPageNumber.append("(");
			sbTxtPageNumber.append(currentCompIndex + 1);
			sbTxtPageNumber.append(" of ");
			sbTxtPageNumber.append(lastComponent + 1);
			sbTxtPageNumber.append(")");
			txtPageNumber.setText(sbTxtPageNumber.toString());

		}

		else
		{
			// printMessage("View Group Null Include header");
			showShortToast(Messages.NO_SURVEY_DETAIL);
		}
	}

	@Override
	protected void initUiVars()
	{
		super.initUiVars();
		btnNext = (Button) findViewById(R.id.btnNext);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);

		banner = (AppBucksBanner) findViewById(R.id.banner);

		txtPageNumber = (TextView) findViewById(R.id.txtPageNumber);

		pbImageLoading = (ProgressBar) findViewById(R.id.pbImageLoading);

	}

	@Override
	protected void performActionOnVideoControl(
			SurveyDetailPojo surveyDetailPojo, View view)
	{

		String vid = surveyDetailPojo.getControlParameter();

		ImageView iv = null;

		int index = 0;
		if (surveyDetailPojo.getControlText() != null
				&& surveyDetailPojo.getControlText().length() > 0)
		{
			{
				index++;
			}

		}
		iv = (ImageView) ((ViewGroup) view).getChildAt(index);
		int urlHash = Helper.getHashNameFromUrl(vid);
		iv.setId(urlHash);
		imageViews.put(urlHash, iv);
		videoUrls.put(urlHash, vid);
		iv.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				String vidUrl = videoUrls.get(v.getId());

				if (vidUrl.contains("youtube"))
				{

					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(vidUrl));
					startActivity(intent);
				} else
				{

					switchScreenTo(VideoScreen.class, VideoPlayer.TYPE_GENERIC
							+ vidUrl);
				}

			}
		});

		// If video type is not youtube we don't have preview image so display
		// preview image from resource

		if (!vid.contains("youtube") && iv != null)
			iv.setImageResource(R.drawable.nopreview);

	}

	private void refreshControlsVisibility()
	{

		for (View view : views)
		{
			view.setVisibility(View.GONE);
		}
		views.get(currentCompIndex).setVisibility(View.VISIBLE);

		refreshButtonsState();
	}

	private void refreshControlsVisibility(byte direction)
	{

		views.get(currentCompIndex).setVisibility(View.VISIBLE);
		if (direction == 1)
		{

			if (currentCompIndex > 0 && currentCompIndex < views.size())
			{

				views.get(currentCompIndex - 1).setVisibility(View.GONE);

			}
		} else
		{

			if (currentCompIndex >= 0 && currentCompIndex < views.size())
			{
				views.get(currentCompIndex + 1).setVisibility(View.GONE);
			}
		}

		refreshButtonsState();
	}

	private void refreshButtonsState()
	{
		if (currentCompIndex == 0)
		{
			btnPrevious.setEnabled(false);
		}
		if (currentCompIndex == lastComponent)
		{
			btnNext.setEnabled(false);
			btnSubmit.setVisibility(View.VISIBLE);
		}
		if (currentCompIndex > 0)
		{
			btnPrevious.setEnabled(true);
		}
		if (currentCompIndex < lastComponent)
		{
			btnNext.setEnabled(true);
		}

	}

	@Override
	protected void performActionOnImageControl(
			SurveyDetailPojo surveyDetailPojo, View view)
	{

		String imgUrl = surveyDetailPojo.getControlParameter();
		imageUrls.add(imgUrl);

		int index = 0;
		if (surveyDetailPojo.getControlText() != null
				&& surveyDetailPojo.getControlText().length() > 0)
		{
			{
				index++;
			}

		}
		ImageView v = (ImageView) ((ViewGroup) view).getChildAt(index);
		imageViews.put(Helper.getHashNameFromUrl(imgUrl), v);

	}

	private boolean clickable = true;

	@Override
	public void btnClick(View v)
	{

		super.btnClick(v);
		int id = v.getId();
		if (id == R.id.btnNext && clickable)
		{
			clickable = false;
			onBtnNext();
			clickable = true;

		} else if (id == R.id.btnPrevious && clickable)
		{
			clickable = false;
			onBtnPrevious();
			clickable = true;
		}
	}

	private void onBtnPrevious()
	{

		currentCompIndex--;
		refreshPagignationText();

		showImageHandler();
		byte reverse = 0;
		refreshControlsVisibility(reverse);

	}

	private void refreshPagignationText()
	{
		StringBuilder sbTxtPageNumber = new StringBuilder();
		sbTxtPageNumber.append("(");
		sbTxtPageNumber.append(currentCompIndex + 1);
		sbTxtPageNumber.append(" of ");
		sbTxtPageNumber.append(lastComponent + 1);
		sbTxtPageNumber.append(")");
		txtPageNumber.setText(sbTxtPageNumber);
	}

	private void onBtnNext()
	{

		currentCompIndex++;
		refreshPagignationText();

		showImageHandler();
		byte forward = 1;
		refreshControlsVisibility(forward);

	}

	@Override
	public void onBackPressed()
	{

		super.onBackPressed();
		imageDownloader.cancel(true);
	}

	private void showImageHandler()
	{
		SurveyDetailPojo sdp = sdps.get(currentCompIndex);

		if (sdp.getControlType() == ControlFactory.CONTROL_IMAGE_VIEW
				|| sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
		{
			int key = Helper.getHashNameFromUrl(sdp.getControlParameter());

			DownloadStatus status = downloadTracker.get(key);
			if (status == null)
			{
				pbImageLoading.setVisibility(View.VISIBLE);
				return;
			}

			if (status.isDownloaded())
			{
				if (null != focusedImage && !focusedImage.isRecycled())
				{
					focusedImage.recycle();
					focusedImage = null;
				}
				focusedImage = Helper.decode(Helper.getTempFile(key + ""), 3);

				imageViews.get(key).setImageBitmap(focusedImage);
				pbImageLoading.setVisibility(View.GONE);
			} else if (status.isError())
			{

				if (sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
				{
					imageViews.get(key).setImageDrawable(
							getResources()
									.getDrawable(R.drawable.video_preview));
				} else if (sdp.getControlType() == ControlFactory.CONTROL_VIDEO_VIEW)
				{
					imageViews.get(key).setImageDrawable(
							getResources().getDrawable(R.drawable.nopreview));
				}

				pbImageLoading.setVisibility(View.GONE);
			} else
			{
				pbImageLoading.setVisibility(View.VISIBLE);
			}
		} else
		{
			pbImageLoading.setVisibility(View.GONE);
		}
	}

	private class DownloadImageFile extends AsyncTask<String, Integer, String>
	{

		protected void onPreExecute()
		{

			super.onPreExecute();

		}

		protected String doInBackground(String... url)
		{

			try
			{

				String imageUrl = survey.getbGImageUrl();
				if (null != imageUrl && imageUrl.length() > 0)
				{

					String outputfile = Helper.getTempFile(Helper
							.getHashNameFromUrl(imageUrl) + "");
					if (imageDownloader.isCancelled())
					{
						return null;
					}
					if (!new File(outputfile).exists())
						Helper.downloadFile(imageUrl, outputfile);

					if (imageDownloader.isCancelled())
					{
						return null;
					}
					survey.setBgImageBitmap(Helper.decode(outputfile, 3));
				}
				publishProgress(5);
			} catch (Exception e)
			{

			}

			int size = imageUrls.size();

			DownloadStatus status = null;
			for (int i = 0; i < size; i++)
			{
				String imgUrl = imageUrls.get(i);

				status = new DownloadStatus();
				int imgHashName = Helper.getHashNameFromUrl(imgUrl);

				status.setHashUrl(imgHashName);
				String local = Helper.getTempFile(imgHashName + "");

				if (Helper.isFileExist(local))
				{
					status.setDownloaded(true);

				} else
				{
					try
					{
						if (imageDownloader.isCancelled())
						{
							return null;
						}
						Helper.downloadFile(imgUrl, local);
						if (imageDownloader.isCancelled())
						{
							return null;
						}
						status.setDownloaded(true);

					} catch (IOException e)
					{
						status.setDownloaded(false);
						status.setError(true);

						Log.e(SurveyDetailSingleControl.class.getSimpleName(),
								"Download Failed: " + imgUrl);

					}

				}
				downloadTracker.put(imgHashName, status);
				byte ctrlTyle = sdps.get(currentCompIndex).getControlType();
				if (ctrlTyle == ControlFactory.CONTROL_IMAGE_VIEW
						|| ctrlTyle == ControlFactory.CONTROL_VIDEO_VIEW)
					publishProgress(10);

			}
			// If video type is youtube we get preview image from youtube using
			// http://i.ytimg.com/vi/" + Youtube Video Id + "/0.jpg
			// If video type is any other we don't have preview image so we just
			// display no preview image from resource

			size = videoUrls.size();

			for (int i = 0; i < size; i++)
			{
				status = new DownloadStatus();
				String videoUrl = videoUrls.valueAt(i);
				byte videoType = 0;
				if (videoUrl.contains("youtube"))
				{

					String yId = YouTubeUtility.getVideoIdFromUrl(videoUrl);
					String vImg = "http://i.ytimg.com/vi/" + yId + "/0.jpg";
					int hash = Helper.getHashNameFromUrl(videoUrl);
					String videoPreviewImgPath = Helper.getTempFile(hash + "");

					if (Helper.isFileExist(videoPreviewImgPath))
					{
						status.setDownloaded(true);

					} else
					{
						try
						{
							if (imageDownloader.isCancelled())
							{
								return null;
							}
							status.setDownloaded(false);
							Helper.downloadFile(vImg, videoPreviewImgPath);
							status.setDownloaded(true);

							if (imageDownloader.isCancelled())
							{
								return null;
							}

						} catch (IOException e)
						{
							status.setDownloaded(false);
							status.setError(true);
							printMessage("Helper.downloadFile(imgProductUrl, productImgPath)");

						}

					}

				} else
				{
					videoType = VideoPlayer.TYPE_GENERIC;
					status.setDownloaded(true);
				}

				downloadTracker
						.put(Helper.getHashNameFromUrl(videoUrl), status);
				byte ctrlTyle = sdps.get(currentCompIndex).getControlType();
				if (ctrlTyle == ControlFactory.CONTROL_IMAGE_VIEW
						|| ctrlTyle == ControlFactory.CONTROL_VIDEO_VIEW)
					publishProgress(10);
			}

			return null;
		}

		protected void onPostExecute(String result)
		{

			super.onPostExecute(result);

		}

		protected void onProgressUpdate(Integer... values)
		{

			super.onProgressUpdate(values);
			if (imageDownloader.isCancelled())
			{
				return;
			}

			if (values[0] == 5)
			{
				if (survey.getBgImageBitmap() != null
						&& !survey.getBgImageBitmap().isRecycled())
				{

					ivBgImage.setBackgroundDrawable(new BitmapDrawable(survey
							.getBgImageBitmap()));

				} else
				{
					ivBgImage.setVisibility(View.GONE);
				}
			} else if (values[0] == 10)

			{
				showImageHandler();
			}

		}

	}

	@Override
	protected void onRelease()
	{
		headerImage.setBackgroundDrawable(null);
		if (null != imageViews)
		{
			int size = imageViews.size();
			for (int i = 0; i < size; i++)
			{
				imageViews.valueAt(i).setImageBitmap(null);

			}
			imageViews.clear();
			imageViews = null;
		}

		if (null != imageDownloader
				&& imageDownloader.getStatus() == Status.RUNNING)
		{
			imageDownloader.cancel(true);

		}

		if (null != survey)
		{
			survey.getSurveyDetail().clear();
			survey.setSurveyDetail(null);

			if (survey.getBgImageBitmap() != null
					&& !survey.getBgImageBitmap().isRecycled())
			{
				survey.getBgImageBitmap().recycle();
				survey.setBgImageBitmap(null);
			}

			survey = null;
		}

		if (null != sdps)
		{
			sdps.clear();
			sdps = null;
		}
		if (null != views)
		{
			views.clear();
		}

		ivBgImage.setBackgroundDrawable(null);

		if (null != downloadTracker)
		{
			downloadTracker.clear();
			downloadTracker = null;
		}

		if (null != focusedImage && !focusedImage.isRecycled())
		{
			focusedImage.recycle();
			focusedImage = null;
		}

	}

	static final class DownloadStatus
	{

		private int hashUrl;

		private boolean downloaded = false;
		private boolean error = false;

		public DownloadStatus()
		{

		}

		public boolean isDownloaded()
		{
			return downloaded;
		}

		public void setDownloaded(boolean downloaded)
		{
			this.downloaded = downloaded;
		}

		public boolean isError()
		{
			return error;
		}

		public void setError(boolean error)
		{
			this.error = error;
		}

		public int getHashUrl()
		{
			return hashUrl;
		}

		public void setHashUrl(int hashUrl)
		{
			this.hashUrl = hashUrl;
		}

	}

	@Override
	protected void onEmptyFieldException(int controlIndex)
	{

		currentCompIndex = controlIndex;
		refreshPagignationText();
		refreshControlsVisibility();

	}

}
